package com.cn.shuangzi.userinfo.activity;

import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.cn.shuangzi.activity.SZInterfaceActivity;
import com.cn.shuangzi.retrofit.SZCommonResponseListener;
import com.cn.shuangzi.retrofit.SZRetrofitManager;
import com.cn.shuangzi.userinfo.BasePhotoActivity;
import com.cn.shuangzi.userinfo.R;
import com.cn.shuangzi.userinfo.bean.OSSTokenInfo;
import com.cn.shuangzi.userinfo.common.OSSManager;
import com.cn.shuangzi.util.SZImageLoader;
import com.cn.shuangzi.util.SZToast;
import com.cn.shuangzi.util.SZUtil;
import com.cn.shuangzi.util.SZValidatorUtil;
import com.cn.shuangzi.view.AlertWidget;
import com.cn.shuangzi.view.pop.BottomCtrlPop;
import com.cn.shuangzi.view.pop.FilterPop;
import com.cn.shuangzi.view.pop.common.CtrlItem;
import com.cn.shuangzi.view.shape_imgview.CustomShapeImageView;
import com.google.gson.Gson;

import org.devio.takephoto.model.TResult;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by CN on 2018-1-25.
 */

public abstract class SZUserInfoActivity extends BasePhotoActivity implements SZInterfaceActivity {
    protected RelativeLayout rltHeadPortrait;
    protected CustomShapeImageView imgHeadPortrait;
    protected RelativeLayout rltNickname;
    protected TextView txtNickname;
    protected SZImageLoader imageLoader;
    private AlertWidget alertWidgetNickname;

    private String objNameAvatar;
    private String path;

    @Override
    protected int onGetChildView() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void onBindChildViews() {
        rltHeadPortrait = findViewById(R.id.rltHeadPortrait);
        imgHeadPortrait = findViewById(R.id.imgHeadPortrait);
        rltNickname = findViewById(R.id.rltNickname);
        txtNickname = findViewById(R.id.txtNickname);
    }

    @Override
    protected void onBindChildListeners() {
        rltNickname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertNickname();
            }
        });
        rltHeadPortrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAvatarPop();
            }
        });
    }

    @Override
    protected void onChildViewCreated() {
        onChildViewCreatedPre();
        showBackImgLeft(getBackImgLeft());
        setTitleTxt(R.string.txt_user_info);
        imageLoader = new SZImageLoader(this);
        loadView();
    }

    @Override
    protected void onReloadData(boolean isRefresh) {

    }

    public void loadView() {
        txtNickname.setText(getNickname());
        imageLoader.load(imgHeadPortrait, getAvatar(), getAvatarPlaceHolder());
    }


    public void alertNickname() {
        if(alertWidgetNickname!=null){
            alertWidgetNickname.close();
        }
        alertWidgetNickname = new AlertWidget(this);
        alertWidgetNickname.showCustomEdit(getString(R.string.txt_user_info),
                getString(R.string.txt_nickname), null, getNickname(), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EditText edtTxtContent = alertWidgetNickname.getWindow().findViewById(R.id.edtTxtContent);
                        String nickname = edtTxtContent.getText().toString().trim();
                        if (SZValidatorUtil.isValidString(nickname)) {
                            alertWidgetNickname.close();
                            modifyNickname(nickname);
                        } else {
                            SZToast.warning("昵称不能为空！");
                        }
                    }
                });
        if (!alertWidgetNickname.isDialogShow()) {
            alertWidgetNickname.show();
        }
    }

    public void modifyNickname(final String nickname){
        showBar();
        request(SZRetrofitManager.getInstance().getSZRequest().updateUserInfo(getUserId(), nickname, null)
                , new SZCommonResponseListener() {
                    @Override
                    public void onResponseSuccess(String data) {
                        closeBar();
                        SZToast.success("昵称修改成功！");
                        onModifyNickname(nickname);
                        txtNickname.setText(getNickname());
                    }

                    @Override
                    public void onResponseError(int errorCode, String errorMsg) {
                        closeBar();
                    }
                });
    }
    private BottomCtrlPop bottomCtrlPop;

    public void showAvatarPop() {
        if (bottomCtrlPop == null) {
            List<CtrlItem> ctrlItemList = new ArrayList<>();
            ctrlItemList.add(new CtrlItem(getString(R.string.txt_take_capture), R.string.txt_take_capture));
            ctrlItemList.add(new CtrlItem(getString(R.string.txt_pick_from_gallery), R.string.txt_pick_from_gallery));
            bottomCtrlPop = new BottomCtrlPop(this, ctrlItemList, new FilterPop.OnItemClickListener() {
                @Override
                public void onItemChecked(int position, CtrlItem ctrlItem) {
                    if (ctrlItem.getText().equals(getString(R.string.txt_take_capture))) {
                        pickFromCaptureCrop();
                    } else if (ctrlItem.getText().equals(getString(R.string.txt_pick_from_gallery))) {
                        pickFromGalleryCrop();
                    }
                }
            });
        }
        bottomCtrlPop.showOnAnchorFromBottom(getBaseView());
    }

    @Override
    public void onTakePhotoSuccess(TResult result) {
        showBar();
        path = result.getImage().getCompressPath();
        getSign();
    }
    public void getSign(){
        request(SZRetrofitManager.getInstance().getSZRequest().getSTSSign(), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                OSSTokenInfo ossTokenInfo = new Gson().fromJson(data,OSSTokenInfo.class);
                uploadOSSFile(ossTokenInfo.getAccessKeyId(),ossTokenInfo.getAccessKeySecret(),ossTokenInfo.getSecurityToken());
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                closeBar();
            }
        });
    }
    public void uploadOSSFile(final String accessKeyId, final String secretKeyId, final String securityToken){
        new Thread(){
            @Override
            public void run() {
                super.run();
                new OSSManager(accessKeyId,secretKeyId,securityToken).uploadWithMD5Verify(path, new OSSManager.OSSUploadProgressListener() {
                    @Override
                    public void onUpload(String uploadFilePath, PutObjectRequest request, long currentSize, long totalSize) {
                    }

                    @Override
                    public void onSuccess(String uploadFilePath, String objName, PutObjectRequest request, PutObjectResult result) {
                        objNameAvatar = objName;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                save();
                            }
                        });
                    }

                    @Override
                    public void onFailure(String uploadFilePath) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                closeBar();
                                SZUtil.log("上传失败了！");
                                objNameAvatar = null;
                                SZToast.error(getString(R.string.error_net_work));
                            }
                        });
                    }
                });
            }
        }.start();

    }
    public void save() {
        if (objNameAvatar == null) {
            closeBar();
            return;
        }
        request(SZRetrofitManager.getInstance().getSZRequest().updateUserInfo(getUserId(),null,getAvatarUrlByObjName(objNameAvatar)), new SZCommonResponseListener() {
            @Override
            public void onResponseSuccess(String data) {
                closeBar();
                onModifyAvatar(getAvatarUrlByObjName(objNameAvatar));
                loadView();
            }

            @Override
            public void onResponseError(int errorCode, String errorMsg) {
                closeBar();
            }
        });
    }

    public abstract String getUserId();

    public abstract String getNickname();

    public abstract String getAvatar();

    public abstract int getAvatarPlaceHolder();

    public abstract String getAvatarUrlByObjName(String objNameAvatar);

    public abstract void onModifyNickname(String nickname);

    public abstract void onModifyAvatar(String avatarUrl);


}
